package com.alks.common.aspect;

import com.alks.common.aop.DarkLock;
import com.alks.entity.exception.ServiceErrorException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerError;
import java.rmi.ServerException;

/**
 * @author MS
 * @since 2024/11/9下午6:25
 */
@Component
@Aspect
public class DarkLockAspect {


    @Pointcut("@annotation(darkLock)")
    public void darkLockPointcut(DarkLock darkLock) {}

    @Around("darkLockPointcut(darkLock)")
    public Object around(ProceedingJoinPoint pjp, DarkLock darkLock) throws Throwable {
        // 获取 HttpServletRequest 对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 从请求中获取 passWord 参数
        String passWord = request.getParameter("password");
        // 判断密码是否存在并与预设的密码进行匹配
        if (passWord != null) {
            if (darkLock.password().equals(passWord)) {
                // 密码匹配，执行目标方法
                return pjp.proceed();
            } else {
                // 密码不匹配
                throw new ServiceErrorException("密码错误");
            }
        } else {
            // 找不到 passWord 参数
            throw new ServiceErrorException("密码错误");
        }
    }
}
